package com.example.duanjunjie.learn.thread;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

/**
 * Created by duanjunjie on 2018/3/7.
 */

public class MyRunnable implements Runnable {

    private Handler mHandler;
    public MyRunnable() {
        Thread thread=new Thread(this);
        thread.start();
    }

    public void test(){
        System.out.println("test"+Thread.currentThread().getName());
    }

    public void sendMsg(){
        for (int i=0;i<10;i++){
            mHandler.sendEmptyMessage(i);
            mHandler.sendEmptyMessageDelayed(i, i*1000);
        }
    }

    public void stop(){
        try {
            if(null != Looper.myLooper()) {
                System.out.println("stop");
                Looper.myLooper().quit();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        Looper.prepare();
        createHandler();
        Looper.loop();
    }

    protected void createHandler(){
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                System.out.println(msg.what);
            }
        };
    }


}
